#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "../source/Buffer.hpp"
#include "http.hpp"

#define WWWROOT "./wwwroot/"

std::string RequestStr(const HttpRequest& req)
{
    std::stringstream ss;
    ss << req._method << " " << req._path << " " << req._version << "\r\n";
    for (const auto& param : req._params)
    {
        ss << param.first << ": " << param.second << "\r\n";
    }
    for (const auto& head : req._headers)
    {
        ss << head.first << ": " << head.second << "\r\n";
    }
    ss << "\r\n";
    ss << req._body;
    return ss.str();
}

void Hello(const HttpRequest& req, HttpResponse* const resp)
{
    resp->SetContent(RequestStr(req), "text/plain");
}

void Login(const HttpRequest& req, HttpResponse* const resp)
{
    resp->SetContent(RequestStr(req), "text/plain");
}

void PutFile(const HttpRequest& req, HttpResponse* const resp)
{
    std::string pathname = WWWROOT + req._path;
    Util::WriteFile(pathname, req._body);
}

void DelFile(const HttpRequest& req, HttpResponse* const resp)
{
    resp->SetContent(RequestStr(req), "text/plain");
}

int main()
{
    HttpServer server(8888);
    server.SetThreadCount(3);
    server.SetBasedir(WWWROOT);
    server.Get("/hello", Hello);
    server.Post("/login", Login);
    server.Put("/1234.txt", PutFile);
    server.Delete("/1234.txt", DelFile);
    server.Listen();

    return 0;
}
